/*
 * @lc app=leetcode.cn id=25 lang=javascript
 *
 * [25] K 个一组翻转链表
 */

// @lc code=start
/**
 * Definition for singly-linked list.
 * function ListNode(val, next) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.next = (next===undefined ? null : next)
 * }
 */
/**
 * @param {ListNode} head
 * @param {number} k
 * @return {ListNode}
 */
var reverseKGroup = function (head, k) {
  if (k === 1) return head;
  const dummy = new ListNode();
  dummy.next = head;
  let preReverseEnd = dummy;

  while (true) {
    let start = preReverseEnd.next;
    let end = start;
    let cnt = 1;
    while (end && cnt < k) {
      end = end.next;
      cnt++;
    }
    if (!end) break;
    const nextGroupHead = end.next;
    const [newHead, newTail] = reverseList(start, k);
    preReverseEnd.next = newHead;
    newTail.next = nextGroupHead;
    preReverseEnd = newTail;
  }

  return dummy.next;
};

function reverseList(start, k) {
  let prev = null;
  let cur = start;
  for (let i = 0; i < k; i++) {
    const next = cur.next;
    cur.next = prev;
    prev = cur;
    cur = next;
  }
  return [prev, start];
}
// @lc code=end
